package com.ifar.audiosdk.api

import android.util.Log
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


abstract class IfarBaseRetrofitClient {

    companion object {
        private const val TIME_OUT = 10L
    }

    private val client: OkHttpClient
        get() {
            //打印retrofit信息部分
            val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
                override fun log(message: String) {
                    //打印retrofit日志
                    Log.e("ifar_retrofit", message)
                }
            })

            val builder = OkHttpClient.Builder()
            builder.connectionPool(ConnectionPool(64, 2, TimeUnit.MINUTES))
            builder.addInterceptor(
                loggingInterceptor.apply {
                    level = HttpLoggingInterceptor.Level.BODY
                })
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)

            handleBuilder(builder)
            return builder.build()
        }

    protected abstract fun handleBuilder(builder: OkHttpClient.Builder)

    fun <S> getService(serviceClass: Class<S>, baseUrl: String): S {
        return Retrofit.Builder()
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(baseUrl)
            .build()
            .create(serviceClass)
    }
}